package zyc.dao.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import zyc.utils.Jdbcutils;

import javax.management.Query;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @description:
 * @author: ZhaoYicong
 * @date: Created in 2020/7/15 21:41
 * @version: v1.0
 * @modified By:
 */
public abstract class BaseDao {
    private QueryRunner queryRunner=new QueryRunner();


    //数据的更新操作

    public int update(String sql,Object...args){
        Connection connection = Jdbcutils.getconnection();
        try {
            int update = queryRunner.update(connection, sql, args);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            Jdbcutils.closeconnection(connection);
        }


        return -1;
    }


    //数据的查询操作  查询单个  返回默认null

    public <T> T queryforone(Class<T> type,String sql,Object...args){

        Connection connection = Jdbcutils.getconnection();
        try {
            T query = queryRunner.query(connection, sql, new BeanHandler<T>(type), args);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            Jdbcutils.closeconnection(connection);
        }
        return null;


    }

    //数据的查询操作  查询多个  返回默认null
    public <T> List<T> queryforlist(Class<T> type, String sql, Object...args){

        Connection connection = Jdbcutils.getconnection();
        try {
            List<T> query = queryRunner.query(connection, sql, new BeanListHandler<T>(type), args);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            Jdbcutils.closeconnection(connection);
        }
        return null;


    }

    //查询 一行一列
    public Object quryforSingleValue(String sql,Object...args){
        Connection connection = Jdbcutils.getconnection();
        try {
            Object query = queryRunner.query(connection, sql, new ScalarHandler(), args);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {

            Jdbcutils.closeconnection(connection);
        }
        return null;


    }
}
